package org.example.struct.array2;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author liyishan
 * @date 2024/3/14 11:12
 * @apiNote
 */

public class Test00003LengthOfLongestSubstring {
    public static void main(String[] args) {
        String s = "abcaaabcd";
        int res = lengthOfLongestSubstring2(s);
        System.out.println(res);
    }
    public int lengthOfLongestSubstring(String s) {
        int max = 0;
        for (int i = 0; i < s.length(); i++) {
            Set<Character> set = new HashSet<>();
            for(int j = i;j<s.length();j++){
                if(set.contains(s.charAt(j))){
                    break;
                }
                set.add(s.charAt(j));
            }
            max = Math.max(max,set.size());
        }
        return max;
    }

    public static int lengthOfLongestSubstring1(String s) {
        Set<Character> occ = new HashSet<>();
        int n = s.length(), ans = 0;
        int r = -1;
        for(int i = 0;i<n;i++){
            if(i!=0){
                occ.remove(s.charAt(i-1));
            }
            while(r < n-1 && !occ.contains(s.charAt(r+1))){
                occ.add(s.charAt(r+1));
                r++;
            }
            ans = Math.max(ans,r+1-i);
        }
        return ans;
    }

    public static int lengthOfLongestSubstring2(String s) {
        char[] chars = s.toCharArray();
        int ans = 0;
        int left = 0;
        Map<Character,Integer> map = new HashMap<>();
        for(int i = 0;i<s.length();i++){
            map.put(chars[i],map.getOrDefault(chars[i],0)+1);
            while(map.getOrDefault(chars[i],0) > 1){
                map.put(chars[left],map.getOrDefault(chars[left],0)-1);
                left++;
            }
            ans = Math.max(ans,i-left+1);
        }
        return ans;
    }
}
